var Fields = {};
var dict_names = [];

window.onload = function() {
	// surenkami pavadinimai į dict_names;
	collectNames();
	console.log("dict_names", dict_names);
	//getOriginalName(dict_names);
	setManagedRadioEvents(setNewName, unsetName);
}

// dar padaryti sąlygą, kad ribotų managinamų žodynų skaičių

function setManagedRadioEvents(setNewName, unsetName) {
	var inputs = document.getElementsByTagName("input");
	for (var i=0; i<inputs.length; i++){
		if (inputs[i].type === "radio") {
			if (inputs[i].value === "manage") {
				eventUtility.addEvent(inputs[i], "change", setNewName);
			} else{
				eventUtility.addEvent(inputs[i], "change", unsetName);
			}
		}
	}
}

function setNewName() {	
	var id = this.name; // kad nebūtų painiavos
	for (var i=0; i<dict_names.length; i++) {
		if (dict_names[i].dict_id === id && !dict_names[i].dict_wasManaged) {
			var newName = getOriginalName(dict_names);
			dict_names[i].dict_newname = newName;
			document.getElementById("new_name_" + id).innerHTML = newName;
			break;
		}		
	}
	console.log("dict_names after set", dict_names);
}

function unsetName() {
	// reikia patikrinti, ar buvo reikšmė manage
	var id = this.name; // kad nebūtų painiavos
	for (var i=0; i<dict_names.length; i++) {
		if (dict_names[i].dict_id === id) {
			if (dict_names[i].dict_newname) {
				dict_names[i].dict_newname = "";
				document.getElementById("new_name_" + id).innerHTML = "";
				console.log("manage; dict_names after unset", dict_names);	
				break;
			}
		}
	}
	console.log ("not manage; unset void");
}

function collectNames(){
	var nameTds = document.getElementsByName("dict_name");
	for (var i = 0; i < nameTds.length; i++) {
		var did =  nameTds[i].getAttribute("dict_index");
		var radios = document.getElementsByName(did);
		var wasManaged;
		for (var j=0; j<radios.length; j++) {
			if (radios[j].checked == true) {
				wasManaged = (radios[j].value === "manage");
			}
		}
		dict_names.push(
				   {dict_id: did, 
					dict_name: nameTds[i].innerHTML,
					dict_wasManaged: wasManaged,
					dict_newname: ""}
				);
	}		
}

function getOriginalName(d_names) {
	var name;
	do {
		name = trim(prompt("Naujas originalus žodyno pavadinimas"));
	} while (!(/^\w+$/.test(name)) || 
			name.length > 7 || 
			!isUnique(name, d_names));
	return name;
}

function isUnique(name, d_names) {
	for (var i = 0; i < d_names.length; i++) {
	    if (d_names[i].dict_name === name || d_names[i].dict_newname === name) {
	    	return false;
	    }
	}
	return true;
}